//引入路由
import router from './router';
//获取token
import { getToken, clearSession } from '@/utils/auth'
//获取store
import { menuStore } from '@/store/menu'

//权限验证处理:全集守卫路由实现
const whiteList = ['/login']; //白名单
router.beforeEach(async (to, from, next) => {
    const store = menuStore()

    //获取token
    let token = getToken();
    if (token) {
        if (to.path === '/login' || to.path === '/') {
            next({ path: '/' })
        } else {
            //从pinia里面获取菜单
            let hasRoles = store.menuList && store.menuList.length > 0
            if (hasRoles) {
                next()
            } else {
                try {
                    //获取菜单、动态生成路由
                    await store.getMenuListAction(router)
                    //确保动态添加的路由已经被完全加载上去
                    next({ ...to, replace: true })
                } catch (error) {
                    //重置token
                    clearSession();
                    //跳到登录
                    next({ path: '/login' })
                }
            }
        }
    } else {
        //判断是否在白名单中
        if (whiteList.indexOf(to.path) !== -1) { //存在白名单，放行
            next();
        } else { //不存在，登录
            next({ path: '/login' })
        }
    }
})
